﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Crank.Core
{
    public class Sql2005DropScripter : Sql2005Scripter, IScripter
    {
        #region IScripter Members

        public void Script(DataModel model, TextWriter output)
        {
            DropLinks(model, output);
            DropTables(model, output);
        }

        private void DropLinks(DataModel model, TextWriter output)
        {
            foreach (var link in model.Links)
                output.WriteLine("IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[{0}]') AND parent_object_id = OBJECT_ID(N'[{1}]'))\nALTER TABLE [{1}] DROP CONSTRAINT [{0}]\nGO\n",
                    ForeignKeyName(link),
                    link.LHS.Name);
        }

        private void DropTables(DataModel model, TextWriter output)
        {
            foreach (var entity in model.Entities.Keys)
                output.WriteLine("IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[{0}]') AND type in (N'U'))\nDROP TABLE [{0}]\nGO\n",
                    entity);
        }

        #endregion
    }
}
